package com.dctp.ems.controller;

import com.dctp.common.cache.FuturesCache;
import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import java.util.ArrayList;
import java.util.List;

@Path("/exchange")
public class ExchangeController extends BaseController {

    /**
     * GET /exchange/list
     * 分页查询交易所
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        String code = getPara("code", "");
        String name = getPara("name", "");
        String status = getPara("status", "");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (StrKit.notBlank(code)) {
            where.append(" AND code LIKE ? ");
            params.add('%' + code + '%');
        }
        if (StrKit.notBlank(name)) {
            where.append(" AND name LIKE ? ");
            params.add('%' + name + '%');
        }
        if (StrKit.notBlank(status)) {
            where.append(" AND status = ? ");
            params.add(status);
        }
        String select = "SELECT * ";
        String from = "FROM dctp_exchange" + where + " ORDER BY display_order ASC, id ASC";
        var p = Db.paginate(page, pageSize, select, from, params.toArray());
        // 填充 futures_name
        List<Record> list = p.getList();
        for (Record rec : list) {
            Long futuresId = rec.getLong("futures_id");
            String futuresName = null;
            if (futuresId != null) {
                Record futures = FuturesCache.get(futuresId);
                if (futures != null) {
                    futuresName = futures.getStr("name");
                }
            }
            rec.set("futures_name", futuresName != null ? futuresName : "");
        }
        renderJson(JsonResult.successWithData(
            new PageResult<>(list, p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * POST /exchange/add
     * 添加交易所
     */
    @Before(Tx.class)
    public void add() {
        Record body = jsonBody();
        if (StrKit.isBlank(body.getStr("code")) || StrKit.isBlank(body.getStr("name"))) {
            renderJson(JsonResult.failWithMessage("交易所编码和名称不能为空"));
            return;
        }
        // 检查唯一
        Long exist = Db.queryLong("SELECT id FROM dctp_exchange WHERE code=?", body.getStr("code"));
        if (exist != null) {
            renderJson(JsonResult.failWithMessage("交易所编码已存在"));
            return;
        }
        body.set("create_time", DateUtil.now());
        if (!Db.save("dctp_exchange", body)) {
            throw new RuntimeException("新增交易所失败");
        }
        renderJson(JsonResult.success());
    }

    /**
     * POST /exchange/update/:id
     * 更新交易所
     */
    @Before(Tx.class)
    public void update() {
        Integer id = getParaToInt(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record body = jsonBody();
        if (body.getColumns().isEmpty()) {
            renderJson(JsonResult.failWithMessage("无有效字段"));
            return;
        }
        // 检查 code 唯一（如果修改了code）
        String newCode = body.getStr("code");
        if (StrKit.notBlank(newCode)) {
            Record old = Db.findById("dctp_exchange", id);
            if (old == null) {
                renderJson(JsonResult.failWithMessage("记录不存在"));
                return;
            }
            if (!newCode.equals(old.getStr("code"))) {
                Long exist = Db.queryLong("SELECT id FROM dctp_exchange WHERE code=? AND id<>?", newCode, id);
                if (exist != null) {
                    renderJson(JsonResult.failWithMessage("交易所编码已存在"));
                    return;
                }
            }
        }
        body.set("id", id)
            .set("update_time", DateUtil.now());
        boolean updated = Db.update("dctp_exchange", body);
        if (!updated) {
            renderJson(JsonResult.failWithMessage("更新失败或记录不存在"));
            return;
        }
        renderJson(JsonResult.success());
    }

    /**
     * POST /exchange/delete/:id
     * 逻辑删除交易所（实际可物理删除）
     */
    @Before(Tx.class)
    public void delete() {
        Integer id = getParaToInt(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        int r = Db.update("DELETE FROM dctp_exchange WHERE id=?", id);
        if (r == 0) {
            renderJson(JsonResult.failWithMessage("删除失败或记录不存在"));
        } else {
            renderJson(JsonResult.success());
        }
    }

    /**
     * GET /exchange/all
     * 获取所有启用状态的交易所
     */
    public void all() {
        List<Record> list = Db.find("SELECT id, code, name FROM dctp_exchange WHERE status = 1 ORDER BY display_order ASC, id ASC");
        renderJson(JsonResult.successWithData(list));
    }
}
